/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { parse } from 'querystring';
import moment from 'moment';
import proSettings from '../../config/defaultSettings';

const reg =
  /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

// 检测用户登录结果
export const checkLoginStatus = (data: { mobile?: string } = {}): boolean => {
  const { mobile } = data || {};
  return !!mobile;
};

// 组装本地缓存key
export const getFormatStorageKey = (key: string) => `VENDOR_${key}`;

// 设置本地缓存
export const setStorage = (key: string, data: any): void => {
  if (window.localStorage) {
    window.localStorage.setItem(getFormatStorageKey(key), JSON.stringify(data));
  }
};

// 获取本地缓存
export const getStorage = (key: string): any => {
  try {
    const result = window.localStorage.getItem(getFormatStorageKey(key));
    return result ? JSON.parse(result) : undefined;
  } catch (error) {
    return undefined;
  }
};

// 移除本地缓存
export const removeStorage = (key: string) =>
  window.localStorage.removeItem(getFormatStorageKey(key));

interface DateCalendarOpts {
  hasTime?: boolean;
  link?: string;
}
export function dateCalendar(val: string, opts: DateCalendarOpts) {
  const { hasTime = true, link = '-' } = opts || {};
  if (val === '0000-00-00 00:00:00') {
    return '';
  }
  const timeFormat = hasTime ? ' HH:mm' : '';
  const dateFormat = `${moment().isSame(val, 'year') ? '' : `YYYY${link}`}MM${link}DD${timeFormat}`;
  const cfg = {
    lastDay: `[昨天]${timeFormat}`,
    sameDay: `[今天]${timeFormat}`,
    nextDay: `[明天]${timeFormat}`,
    lastWeek: dateFormat,
    nextWeek: dateFormat,
    sameElse: dateFormat,
  };
  const m = moment(val);
  return val && m.isValid() ? m.calendar(null, cfg) : val;
}

/**
 *
 * @description 检查是否在微信环境打开
 * @returns string;
 */
export function checkInMicroMessenger(): string {
  const { openInMicroMessenger } = proSettings;
  if (process.env.NODE_ENV === 'development' || !openInMicroMessenger) {
    return '';
  }
  const useragent = navigator.userAgent;
  const isWxWork = openInMicroMessenger === 'wxwork'; // 企业微信
  const inMicroMessenger = /MicroMessenger/i.test(useragent);
  if (!inMicroMessenger || (isWxWork && !/wxwork/i.test(useragent))) {
    return '哎呀，看来你拐错弯了';
  }
  return '';
}

export const formattedDigit2 = (number: number): string => {
  if (number >= 10) {
    return String(number);
  } else {
    return '0' + number;
  }
};

/**
 *
 * 加载js
 * @param url
 * @returns
 */
const loadScriptMaps: Record<string, any> = {};
export function loadScript(url: string, timeout: number = 3000): Promise<void> {
  return new Promise((resolve, reject) => {
    if (loadScriptMaps[url]) {
      resolve();
      return;
    }
    let timer: NodeJS.Timeout;
    if (timeout > 0) {
      // 超时加载
      timer = setTimeout(reject, timeout);
    }
    loadScriptMaps[url] = true;
    const script: any = document.createElement('script');
    script.type = 'text/javascript';
    script.defer = 'defer';
    script.async = 'async';
    if (script.readyState) {
      script.onreadystatechange = () => {
        if (script.readyState == 'loaded' || script.readyState == 'complete') {
          script.onreadystatechange = null;
          clearTimeout(timer);
          resolve();
        }
      };
    } else {
      script.onload = () => {
        clearTimeout(timer);
        resolve();
      };
    }
    script.src = url;
    document.body.appendChild(script);
  });
}

/**
 * 格式化金额
 * @param val
 * @returns
 */
export const formatMoney = (val: string | number) =>
  `${val && val != 0 ? (Number(val) / 100).toFixed(2) : ''}`;
